<template>
  <div class="pic-captcha" @click="refresh">
    <div v-if="svg" class="svg" v-html="svg" />
    <img v-else-if="base64" class="base64" :src="base64" alt="" />

    <template v-else>
      <var-icon name="refresh" />
    </template>
  </div>
</template>

<script lang="ts" setup>
import { service } from '@/apis/index'
import { onMounted, ref } from 'vue'

const emit = defineEmits(['update:modelValue', 'change'])

// base64
const base64 = ref('')

// svg
const svg = ref('')

async function refresh() {
  await service({
    path: '/student/index/captcha',
    method: 'get',
    params: {
      height: 45,
      width: 150,
      color: '#2c3142'
      // type: 'svg'
    }
  })
    .then((req) => {
      const { captchaId, data } = req
      if (data.includes(';base64,')) {
        base64.value = data
      } else {
        svg.value = data
      }
      emit('update:modelValue', captchaId)
      emit('change', {
        base64,
        svg,
        captchaId
      })
    })
    .catch((err) => {
      console.error(err)
      Snackbar.error(err.message)
    })
}

onMounted(() => {
  refresh()
})

defineExpose({
  refresh
})
</script>

<style lang="scss">
.pic-captcha {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  height: 45px;
  width: 150px;
  position: relative;

  .svg {
    height: 100%;
    position: relative;
  }

  .base64 {
    height: 100%;
  }

  .el-icon {
    position: absolute;
    font-size: 22px;
    right: 20px;
  }
}
</style>
